package com.changgou.order.service.impl;

import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.feign.SpuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.goods.pojo.Spu;
import com.changgou.order.pojo.OrderItem;
import com.changgou.order.service.CartService;
import entity.RedisConfig;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartServiceImpl implements CartService {


    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SkuFeign skuFeign;
    @Autowired
    private SpuFeign spuFeign;

    @Override
    public void add(Long id, Integer num, String username) {
        //修改redisTemplate的编码方式
        RedisConfig.convertRedisTemplate(redisTemplate);

        if (num <= 0) {
            //删除购物车商品
            redisTemplate.boundHashOps("Cart_" + username).delete(id.toString());
            return;
        }

        Result<Sku> skuResult = skuFeign.findById(id);
        if (skuResult != null && skuResult.isFlag()) {
            Sku sku = skuResult.getData();
            //获取spu
            Result<Spu> spuResult = spuFeign.findById(sku.getSpuId());
            //将商品信息封装成OrderItem
            OrderItem orderItem = skuToOrderItem(sku, spuResult.getData(), num);
            /****
             * 将商品存入redis购物车中
             * namespace = Cart_username
             * key=id(sku)
             * value=OrderItem
             */
            redisTemplate.boundHashOps("Cart_" + username).put(id.toString(), orderItem);
        }
    }

    @Override
    public List<OrderItem> list(String username) {
        RedisConfig.convertRedisTemplate(redisTemplate);
        return redisTemplate.boundHashOps("Cart_" + username).values();
    }

    private OrderItem skuToOrderItem(Sku sku, Spu spu, Integer num) {
        OrderItem orderItem = new OrderItem();
        //产品分类
        orderItem.setCategoryId1(spu.getCategory1Id());
        orderItem.setCategoryId2(spu.getCategory2Id());
        orderItem.setCategoryId3(spu.getCategory3Id());

        orderItem.setSpuId(spu.getId());
        orderItem.setSkuId(sku.getId());
        orderItem.setName(sku.getName());
        orderItem.setPrice(sku.getPrice());
        orderItem.setNum(num);
        orderItem.setMoney(sku.getPrice() * num);
        orderItem.setPayMoney(sku.getPrice() * num);
        orderItem.setImage(sku.getImage());
        orderItem.setWeight(sku.getWeight() * num);

        return orderItem;
    }
}
